package com.chlitina.store.modules.sys.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chlitina.store.modules.sys.utils.StoreUtils;

public class LoginOutAuthenticationFilter extends LogoutFilter {
    private static final Logger log = LoggerFactory.getLogger(LoginOutAuthenticationFilter.class);

	  @Override
	    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
	        Subject subject = getSubject(request, response);
	        String redirectUrl = getRedirectUrl(request, response, subject);
	        //try/catch added for SHIRO-298:
	        try {
	        	HttpServletRequest httpRequest = (HttpServletRequest)request;
	        	String sessionId = httpRequest.getSession().getId();
	        	if (sessionId != null) {
	        		StoreUtils.sessionLogout(sessionId);
				}
	            subject.logout();
	        } catch (SessionException ise) {
	            log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
	        }
	        issueRedirect(request, response, redirectUrl);
	        return false;
	    }
}
